<template>
  <div class="select-products2">
    <header>
      <p>选择商品</p>
      <div class="action-wrap">
        <!-- <el-button class="ml32" type="primary" @click="getListFun"> 查询 </el-button> -->
        <el-button class="ml10" type="info" plain @click="back"> 返回 </el-button>
      </div>
    </header>

    <div class="content">
      <el-container>
        <el-aside width="200px">
          <el-tree
            :default-expand-all="false"
            :data="treeData"
            :props="{
              children: 'children',
              label: 'name'
            }"
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </el-aside>
        <el-main>
          <div class="left">
            <el-scrollbar>
              <div class="action-wrap">
                <div class="kh-info">
                  <span>客户信息</span>
                  <!-- <el-input
                    class="ml16 mr32 jzt-select-input"
                    v-model="searchkey"
                    clearable
                    style="width: 260px"
                    :disabled="!searchType && searchType !== 0"
                    @keyup.enter="getListFun"
                    @clear="
                      () => {
                        searchType = null;
                        getListFun();
                      }
                    "
                    placeholder="请输入"
                  >
                    <template #prepend>
                      <el-select v-model="searchType" :placeholder="'请选择'" style="width: 100px">
                        <el-option v-for="_item in options" :key="_item.value" :label="_item.label" :value="_item.value" />
                      </el-select>
                    </template>
                  </el-input> -->
                  <el-select
                    class="ml16"
                    v-model="userInfo"
                    multiple
                    clearable
                    collapse-tags
                    placeholder="请选择"
                    popper-class="userinfo-select"
                    style="width: 240px"
                    @change="customerChange"
                  >
                    <template #header>
                      <el-input v-model="searchkey" placeholder="请输入关键词" @input="changeSearchCustomer()">
                        <template #suffix>
                          <img src="@/assets/search.png" alt="" />
                        </template>
                      </el-input>
                    </template>
                    <el-option
                      v-for="item in userList"
                      :key="item.orderId"
                      :label="item.customerName + ' ' + item.customerMobile"
                      :value="item.orderId"
                    />
                  </el-select>
                </div>
                <div class="kh-info">
                  <span>库存数量</span>
                  <el-input-number
                    :min="0"
                    :precision="0"
                    controls-position="right"
                    style="width: 100px"
                    class="ml16"
                    v-model="curProductNum"
                    @change="
                      () => {
                        getListFun();
                      }
                    "
                  ></el-input-number>
                </div>
                <div class="kh-info">
                  <span>供应单价</span>
                  <div class="ml16" style="display: inline-block">
                    <el-input-number
                      :min="0"
                      controls-position="right"
                      style="width: 100px"
                      v-model="startUnitPrice"
                      @change="
                        () => {
                          getListFun();
                        }
                      "
                    ></el-input-number>
                    -
                    <el-input-number
                      :min="0"
                      controls-position="right"
                      style="width: 100px"
                      v-model="endUnitPrice"
                      @change="
                        () => {
                          getListFun();
                        }
                      "
                    ></el-input-number>
                  </div>
                </div>
                <el-input
                  class="searchkey-input"
                  v-model="searchkey2"
                  clearable
                  style="width: 360px"
                  placeholder="请输入商品名、id、sku编码"
                  :suffix-icon="Search"
                  @keyup.enter="getListFun"
                  @clear="
                    () => {
                      getListFun();
                    }
                  "
                />
              </div>
              <el-checkbox-group v-model="checkList" class="list" @change="selectChange">
                <template v-if="list.length > 0">
                  <div class="list-item" v-for="item in list" :key="item.id">
                    <div>
                      <el-checkbox label="" :value="item" />
                      <div class="prod-info">
                        <div class="locks" v-if="item.isOrderBind == 1">
                          <img :src="lock" alt="" />
                        </div>
                        <div class="top">
                          <div class="img"><img :src="item.mainPicUrl" alt="" /></div>
                          <div class="info">
                            <h3 class="name text-over" style="max-width: 300px" :title="item.productAliasName || '-'">
                              {{ item.productAliasName || "-" }}
                            </h3>
                            <p style="white-space: break-spaces">{{ getSpes(item.properties) }}</p>
                            <p>SKU编码：{{ item.skuCode || "-" }}</p>
                            <p style="display: flex; justify-content: space-between">
                              <span>ID：{{ item.productId || "-" }}</span>
                              <span class="price" style="color: #3d3d3d"
                                >供应单价： <i style="font-style: normal; color: #ff3333"> ¥{{ item.buyPrice || "--" }}</i></span
                              >
                            </p>
                          </div>
                        </div>
                        <footer>
                          <p>可用库存数量：{{ item.curProductNum || "-" }}</p>
                          <p>可用库存件数：{{ item.curProductPartNum || "-" }}</p>
                          <p style="text-align: right">
                            {{ item.customer ? item.customer.split(",")[0] + " " + item.customer.split(",")[1] : "-" }}
                          </p>
                        </footer>
                        <!-- 右上仓库角标 -->
                        <div class="warehouse-icon">{{ item.warehouseName || "-" }}</div>
                      </div>
                    </div>
                  </div>
                </template>
                <div v-else style="display: flex; justify-content: center; width: 100%">
                  <el-empty description="暂无数据" />
                </div>
              </el-checkbox-group>
            </el-scrollbar>
          </div>
        </el-main>
      </el-container>
      <div class="action-btn">
        <p class="mr40">
          <el-button type="primary" link :disabled="checkList.length <= 0" @click="drawer = true">
            <p class="f18" style="display: flex; align-items: center">
              <span style="color: #86909c">已选中：</span>{{ checkList.length }}
            </p>
          </el-button>
        </p>
        <el-button
          plain
          type="info"
          @click="
            () => {
              checkList = [];
            }
          "
          >取消</el-button
        >
        <el-button type="primary" :disabled="checkList.length <= 0" @click="save">确认加入盘点单</el-button>
      </div>
    </div>

    <!-- 已选中抽屉 -->
    <el-drawer v-model="drawer" class="jzt-drawer" :direction="'rtl'" modal-class="selected-drawer" :before-close="handleClose">
      <template #header>
        <h4>已选中：{{ checkList.length }}</h4>
      </template>
      <template #default>
        <div class="right">
          <el-scrollbar>
            <template v-if="checkList.length > 0">
              <div class="list">
                <div class="list-item" v-for="item in checkList" :key="item.id">
                  <div class="prod-info">
                    <div class="top pl10">
                      <div class="img"><img :src="item.mainPicUrl" alt="" /></div>
                      <div class="info">
                        <h3 class="name text-over" style="max-width: 200px" :title="item.productAliasName || '-'">
                          {{ item.productAliasName || "-" }}
                        </h3>
                        <p style="white-space: break-spaces">{{ getSpes(item.properties) }}</p>
                        <p>SKU编码：{{ item.skuCode || "-" }}</p>
                        <p style="display: flex; justify-content: space-between">
                          <span>ID：{{ item.productId || "-" }}</span>
                          <span class="price" style="color: #3d3d3d"
                            >供应单价： <i style="font-style: normal; color: #ff3333"> ¥{{ item.buyPrice || "--" }}</i></span
                          >
                        </p>
                      </div>
                    </div>
                    <footer>
                      <p>可用库存数量：{{ item.curProductNum || "-" }}</p>
                      <p>可用库存件数：{{ item.curProductPartNum || "-" }}</p>
                      <p style="text-align: right">
                        {{ item.customer ? item.customer.split(",")[0] + " " + item.customer.split(",")[1] : "-" }}
                      </p>
                    </footer>
                    <!-- 右上仓库角标 -->
                    <div class="warehouse-icon">{{ item.warehouseName || "-" }}</div>
                  </div>
                  <el-button link @click="delRightSku(item)">
                    <img class="del-icon" src="@/assets/images/del.png" alt="" />
                  </el-button>
                </div>
              </div>
            </template>

            <div v-else style="display: flex; justify-content: center; width: 100%">
              <el-empty description="暂无数据" />
            </div>
          </el-scrollbar>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import { pageByKeyword, getShopDetail } from "@/apis/procure/entry";
import { useRoute, useRouter } from "vue-router";
import { getList } from "@/apis/stencil/fittings";
const route = useRoute();
const router = useRouter();
import { getCategoryList, getProductInventory, addSelectProducts } from "@/apis/procure/inventory-allot";
import { ElMessage } from "element-plus";
import { getCategoriesByWarehouseId, searchDetail, saveTempSkuList, getCustomerInfo } from "@/apis/procure/inventory-count";
import {
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import lock from "@/static/images/lock.png";
const warehouseId = ref(route.query.warehouseId);
const optionInfo = ref({ isShow: false, detail: {} });
const searchType = ref("");
const searchkey = ref("");
const searchkey2 = ref("");
const curProductNum = ref(null);
const startUnitPrice = ref(null);
const endUnitPrice = ref(null);
const list = ref([]);
const checkList = ref([]); //选中的skuId
const checkObjs = ref([]); //选中的skuObj
const options = ref([
  { label: "全部", value: 0 },
  { label: "姓名", value: 1 },
  { label: "电话", value: 2 }
]);
const treeData = ref([]);
const userInfo = ref(null);
const userList = ref([{ customerId: 1, customerName: "AAA", customerMobile: "13666666666" }]);
// ============================
const drawer = ref(false);

watch(
  () => checkList.value,
  val => {},
  { deep: true }
);

onMounted(() => {
  getTree();
  getListFun();
  getCustomerList();
});

const selectCustomers = ref([]);
const customerChange = val => {
  console.log(909090, val);
  selectCustomers.value = userList.value.filter(item => val.includes(item.orderId));
  getListFun();
};

const save = () => {
  saveTempSkuList({
    tempId: Number(route.query._time),
    details: checkList.value
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "商品暂存成功！",
        type: "success"
      });
      back();
    }
  });
};

//关闭已选中抽屉
const handleClose = () => {
  drawer.value = false;
};

//点击右侧的删除图标按钮
const delRightSku = item => {
  const index = checkList.value.findIndex(obj => obj.id === item.id);
  if (index >= 0) {
    checkList.value.splice(index, 1);
  }
};

//查询客户列表
const changeSearchCustomer = _debounce(() => {
  getCustomerList();
}, 500);
const getCustomerList = async () => {
  const res = await getCustomerInfo({ warehouseId: warehouseId.value, keyword: searchkey.value });
  userList.value = res.data || [];
};

const getTree = async () => {
  await getCategoriesByWarehouseId({ warehouseId: warehouseId.value }).then(res => {
    treeData.value = res.data || [];
  });
};

const back = () => {
  // console.log(111, route.query._time);
  router.push({
    path: "/procure/inventory-count/add-sku",
    query: { receivingName: route.query.receivingName, warehouseId: warehouseId.value, _time: route.query._time }
  });
};

const selectChange = () => {
  console.log("选中的数据", checkList.value);
};

//点击分类树节点，查询新的sku列表数据
const handleNodeClick = (data, node) => {
  if (data.children.length <= 0) {
    getListFun(data);
  }
};

//查询商品sku列表数据
const getListFun = data => {
  if (startUnitPrice.value > endUnitPrice.value) {
    startUnitPrice.value = 0;
    endUnitPrice.value = 0;
    return ElMessage({
      message: "供应单价最小值必须<=最大值！请重新输入",
      type: "error"
    });
  }
  let params = {
    checkType: 2, //盘点类型;1整仓盘点 2sku盘点
    warehouseId: warehouseId.value,
    categoryId: data ? data.categoryId : "",
    startUnitPrice: startUnitPrice.value,
    endUnitPrice: endUnitPrice.value,
    curProductNum: curProductNum.value,
    keyWord: searchkey2.value,
    page: 1,
    size: 9999,
    customerIds: selectCustomers.value.map(item => item.customerId)
  };
  searchDetail(params).then(res => {
    if (res.code === 200) {
      list.value = res.data.records;
    }
  });
};

const close = () => {
  optionInfo.value.isShow = false;
};

//拼接商品的sku规格
const getSpes = properties => {
  if (!properties) return "-";
  const arr = JSON.parse(properties) || [];
  if (arr.length > 1) {
    const str = arr.reduce((a, b) => {
      return a.specificationVal + "+" + b.specificationVal;
    });
    return str;
  } else if (arr.length === 1) {
    return arr[0].specificationVal;
  } else {
    return "-";
  }
};
</script>

<style lang="scss">
.userinfo-select {
  .el-select-dropdown__header {
    padding: 0 !important;
    .el-input__inner {
      --el-input-inner-height: 36px;
    }
    .el-input__wrapper {
      --el-input-bg-color: white;
    }
  }
}
.selected-drawer {
  .el-drawer {
    width: 500px !important;
    box-shadow: -8px 0px 16px 0px rgba(0, 38, 73, 0.1);
    border-radius: 10px 0px 0px 10px;
  }

  .el-drawer__body {
    width: 500px !important;
    box-sizing: border-box;
    padding-top: 0 !important;
    padding-right: 0 !important;

    .list-item {
      border-radius: 2px;
      margin: 0 0px 10px 0;
      width: 100%;
      box-sizing: border-box;
      padding-right: 20px;
      & > div {
        position: relative;
        background-color: #f5f7fa;
      }

      .el-checkbox {
        position: absolute;
        top: 40px;
        left: 10px;
      }
      .prod-info {
        min-height: 100px;
        font-size: 16px;
        position: relative;
        .info {
          flex: 1;
        }
        .img {
          width: 80px;
          height: 80px;
          border-radius: 4px;
          background-color: #eee;
          margin-right: 20px;
          img {
            width: 100%;
            height: 100%;
            border-radius: 4px;
          }
        }
        h3 {
          font-size: 16px;
          color: #3d3d3d;
          line-height: 22px;
        }
        p {
          font-size: 12px;
          line-height: 20px;
          color: #86909c;
        }
        .top {
          display: flex;
          padding: 10px;
          padding-left: 46px;
        }
        footer {
          display: flex;
          justify-content: space-between;
          padding: 10px;
          border-top: 1px solid #e1e6ed;
          p {
            flex: 1;
          }
        }
        .warehouse-icon {
          position: absolute;
          right: 0;
          top: 0;
          background-color: #d9edff;
          border-radius: 12px 0px 0px 12px;
          font-size: 12px;
          line-height: 24px;
          padding: 0 9px 0 15px;
        }
      }
    }
    .right {
      position: relative;
      .list-item {
        background-color: transparent;
        display: flex;
        .prod-info {
          background-color: #f5f7fa;
          flex: 1;
        }
        .del-icon {
          width: 16px;
          height: 16px;
          margin-left: 20px;
        }
      }
    }
  }
  .el-drawer__header {
    font-size: 18px;
    color: #131414;
    margin-bottom: 32px !important;
    h4 {
      font-weight: normal;
      position: relative;
      padding-left: 14px;
      &::before {
        position: absolute;
        content: "";
        left: 0;
        top: 6px;
        width: 6px;
        height: 6px;
        background-color: #409eff;
        border-radius: 50%;
      }
    }
  }
  .el-drawer__footer {
    text-align: center !important;
  }
}
</style>
<style lang="scss" scoped>
:deep(.el-input-group__append) {
  padding: 0 !important;
}
:deep(.el-tree) {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 94px;

  .el-icon.el-tree-node__expand-icon {
    padding-left: 10px;
  }

  .el-tree-node.is-current > .el-tree-node__content {
    background-color: #d9e8ff !important;
    color: #007dff;

    .custom-tree-node i {
      color: #007dff !important;
    }
  }
}
.select-products2 {
  height: calc(100% - 0px);
  overflow-y: auto;
  padding: 0 20px 0 20px;
  header {
    background-color: white;
    padding: 14px 20px;
    position: sticky;
    top: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.04);
    margin: 0 -20px;
    border-radius: 10px 10px 0 0;
    border-bottom: 1px solid #e2e8f0;
    p {
      color: #131414;
      font-size: 18px;
      position: relative;
      padding-left: 14px;
      &::before {
        position: absolute;
        content: "";
        left: 0;
        top: 8px;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: #409eff;
      }
    }
    .action-wrap {
      display: flex;
    }
  }
  .content {
    height: calc(100% - 64px);
    margin: 0 -20px;

    .action-btn {
      position: absolute;
      height: 76px;
      bottom: 0;
      left: 0px;
      right: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      box-shadow: 2px -4px 8px 0px rgba(66, 78, 102, 0.1);
      background-color: white;
      padding-right: 20px;
      z-index: 2;
    }
    :deep(.el-container) {
      height: 100%;
    }

    :deep(.el-aside) {
      height: 100%;
      overflow-y: auto;
      padding: 14px 0;
      box-sizing: border-box;
      padding-bottom: 76px;
      .el-tree {
        padding-bottom: 10px !important;
      }
    }
    :deep(.el-main) {
      height: 100%;
      overflow-y: auto;
      border-left: 1px solid #e2e8f0;
      display: flex;
      padding: 0;
      & > div {
        flex: 1;
      }
      .list {
        display: flex;
        flex-wrap: wrap;
      }
      .list-item {
        border-radius: 2px;
        margin: 0 0px 10px 0;
        width: 50%;
        box-sizing: border-box;
        & > div {
          position: relative;
          background-color: #f5f7fa;
        }
        &:nth-of-type(2n + 1) {
          padding-right: 10px;
        }
        &:nth-of-type(2n) {
          padding-left: 10px;
        }

        .el-checkbox {
          position: absolute;
          top: 40px;
          left: 10px;
        }
        .prod-info {
          min-height: 100px;
          font-size: 16px;
          position: relative;
          .locks {
            position: absolute;
            left: 0;
            top: 0;
            img {
              width: 20px;
            }
          }
          .info {
            flex: 1;
          }
          .img {
            width: 80px;
            height: 80px;
            border-radius: 4px;
            background-color: #eee;
            margin-right: 20px;
            img {
              width: 100%;
              height: 100%;
              border-radius: 4px;
            }
          }
          h3 {
            font-size: 16px;
            color: #3d3d3d;
            line-height: 22px;
          }
          p {
            font-size: 12px;
            line-height: 20px;
            color: #86909c;
          }
          .top {
            display: flex;
            padding: 10px;
            padding-left: 46px;
          }
          footer {
            display: flex;
            justify-content: space-between;
            padding: 10px;
            border-top: 1px solid #e1e6ed;
            p {
              flex: 1;
            }
          }
          .warehouse-icon {
            position: absolute;
            right: 0;
            top: 0;
            background-color: #d9edff;
            border-radius: 12px 0px 0px 12px;
            font-size: 12px;
            line-height: 24px;
            padding: 0 9px 0 15px;
          }
        }
      }
      .left {
        padding: 20px 20px 76px 20px;

        .action-wrap {
          display: flex;
          justify-content: space-between;
          position: sticky;
          top: 0;
          z-index: 2;
          background-color: white;
          padding-bottom: 20px;
          .searchkey-input {
            .el-input__wrapper {
              background-color: white;
              border: 1px solid #dcdfe6;
              border-radius: 4px;
            }
          }
        }

        .el-checkbox {
          .el-checkbox__inner {
            border-radius: 50%;
            display: inline-block;
            width: 16px;
            height: 16px;

            &::before {
              text-align: center;
              left: 8px;
              top: 0px;
            }

            &::after {
              font-size: 12px;
              text-align: center;
              left: 5px;
              top: 2px;
              width: 4px;
            }
          }
        }
      }
      .right {
        padding: 20px 0 76px 20px;
        border-left: 1px solid #e2e8f0;
        position: relative;
        .list-item {
          background-color: transparent;
          display: flex;
          .prod-info {
            background-color: #f5f7fa;
            flex: 1;
            position: relative;
          }
          .info {
            flex: 1;
          }
          .del-icon {
            width: 16px;
            height: 16px;
            margin-left: 20px;
          }
        }
      }
    }
  }
}
</style>
